package com.itzdm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzdm.reggie.common.constant.MessageConstant;
import com.itzdm.reggie.common.exception.LoginFailedException;
import com.itzdm.reggie.entity.User;
import com.itzdm.reggie.mapper.UserMapper;
import com.itzdm.reggie.service.UserService;
import com.itzdm.reggie.utils.MailUtils;
import com.itzdm.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sendMsg(User user, HttpSession session) {
        String phone = user.getPhone();
        if (!phone.isEmpty()){
            String code = MailUtils.achieveCode();
            log.info("code:{}",code);
            try {
                MailUtils.sendTestMail(phone,code);
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public User login(Map map, HttpSession session) {
        //map中获取手机号
        String  phone = map.get("phone").toString();
        //map中获取验证码
        String code = map.get("code").toString();
        //session中获取code
//        String codeInSession = session.getAttribute(phone).toString();
        //redis中获取验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        //比对code
        if (codeInSession != null && codeInSession.equalsIgnoreCase(code)){
            //如果比对成功，查询数据库中是否存在该用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = getOne(queryWrapper);
            if (user == null){
                //为空时，自动完成注册
                user = new User();
                user.setPhone(phone);
                save(user);
            }

            session.setAttribute("user",user.getId());
            // 如果登陆成功，将缓存中的验证码删除
            redisTemplate.delete(phone);
            return user;
        }
        throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
    }
}
